<template>
    <div class="bodyone">
        <div class="bodytow">
            <div class="login">登录</div>
            <Form ref="formRef" :rules="formRules" :model-value="formData" @submit="handleSubmit">
                <div class="span_input">
                    <span class="span">用户名: </span>
                    <Input name="username" v-model="formData.username" placeholder="请输入用户名" />
                </div>
                <div class="span_input">
                    <span class="span">密码: </span>
                    <Input name="password" v-model="formData.password" placeholder="请输入密码" />
                </div>
                <div class="anniu">
                    <button class="btn antd-btn" @click="handleReset">
                        重置
                    </button>
                    <button class="btn antd-btn" @click="routerPage">
                        登录
                    </button>
                </div>
            </Form>
        </div>
    </div>
</template>
<!-- 实现登录的流程： -->
<!-- 双token和无感刷新 -->
<script setup lang="ts">
import { ref, reactive } from "vue";
import Input from "../components/BaseInput.vue";
import Form from "../components/BaseForm.vue";
import { useLogin } from "../hooks/user";
import { useRouter } from "vue-router";
const router = useRouter();

const formRef = ref<InstanceType<typeof Form> | null>(null);
const formData = reactive({
    username: "",
    password: "",
})
const userInfo = ref({ username: '', password: '' })
const { refetch, data, isLoading, isError } = useLogin(() => userInfo.value);

// 表单校验规则
const formRules = [
    {
        name: 'username',
        trigger: 'blur',
        type: 'Required',
        errorMsg: '用户名不能为空'
    },
    {
        name: 'password',
        trigger: 'blur',
        type: 'Required',
        errorMsg: '密码不能为空'
    }
]
interface FormData {
    username: string;
    password: string;
}
// 处理表单提交
const handleSubmit = async (formData: FormData, isValid: boolean) => {
    if (isValid) {
        console.log(formData);
        // 这里可以添加实际得到登录逻辑, 调用接口, 进行登录操作
        // 自定义组合式函数, 只能放在setup函数里面调用
        userInfo.value = formData; // 更新用户表单
        await refetch(); // 重新调用接口
        console.log(data, isLoading, isError, '登录按钮');
    } else {
        console.log('表单校验失败');
    }
}

const handleReset = () => {
    formData.username = "";
    formData.password = "";
    // // 重置校验状态
    if (formRef.value) {
        // 可以在这里添加重置校验状态的逻辑
        formRef.value.resetValidation();
    }
}

const routerPage = () => {
    router.push("/home");
    // 实现登录的逻辑, 前端需要有表单的校验
}
</script>

<style lang="scss" scoped></style>